package v1

import (
	"fmt"
	"net/http"
	"server/global"
	"server/global/e"
	"server/global/response"
	"server/service"

	"github.com/gin-gonic/gin"
)

// @Summary Import Bin
// @Produce  json
// @Param bin formData file true "Bin File"
// @Success 200 {object} response.Response
// @Failure 500 {object} response.Response
// @Router /api/v1/tags/import [post]
func UploadBin(c *gin.Context) {
	r := response.Gin{C: c}
	file, bin, err := c.Request.FormFile("file")

	if err != nil {
		global.LOG.Warn(fmt.Sprintf("%v", err))
		r.Response(http.StatusInternalServerError, e.ERROR, nil)
		return
	}

	if bin == nil {
		r.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	// bin_name := bin.Filename
	// url_path := global.CONFIG.Upload.Url + "/" + global.CONFIG.Upload.BinPath
	// bin_path := global.CONFIG.Upload.BinPath

	// binName := service.GetBinName(bin.Filename)
	binName := bin.Filename
	binPath := service.GetBinPath()
	fullPath := binPath + "/" + binName

	// 检测文件类型
	if !service.CheckBinExt(binName) {
		r.Response(http.StatusBadRequest, e.ERROR_UPLOAD_EXTS, nil)
		return
	}

	// 检测文件大小
	if !service.CheckBinSize(file) {
		r.Response(http.StatusBadRequest, e.ERROR_UPLOAD_SIZE, nil)
		return
	}

	// 检测文件夹
	err = service.CheckBin(binPath)
	if err != nil {
		global.LOG.Warn(fmt.Sprintf("%v", err))
		r.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_CHECK, nil)
		return
	}

	// 保存文件
	if err := c.SaveUploadedFile(bin, fullPath); err != nil {
		global.LOG.Warn(fmt.Sprintf("%v", err))
		r.Response(http.StatusInternalServerError, e.ERROR_UPLOAD_SAVE, nil)
		return
	}

	r.Response(http.StatusOK, e.SUCCESS, map[string]string{
		"file_name":     binName,
		"file_url":      service.GetBinFullUrl(binName),
		"file_save_url": fullPath,
	})
}
